package com.education.service.task;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 任务线程池配置类
 * @author Jason
 * @version 1.0.0
 * @date 2021-11-20 23:58
 */
@Configuration
public class TaskBeanConfig {
    /**
     * CPU个数
     */
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_SIZE = CPU_COUNT * 2;
    private static final int MAX_CORE_SIZE = CPU_COUNT * 4;

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(CORE_SIZE);
        threadPoolTaskExecutor.setMaxPoolSize(MAX_CORE_SIZE);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }

    @Bean
    public TaskManager taskManager (ThreadPoolTaskExecutor threadPoolTaskExecutor) {
        return new TaskManager(threadPoolTaskExecutor);
    }
}
